package org.millioncall.yueyoga.admin.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.util.DateTimeUtils;
import org.millioncall.openplatform.util.EncryptUtils;
import org.millioncall.openplatform.util.WebAppUtils;
import org.millioncall.yueyoga.admin.model.Account;
import org.millioncall.yueyoga.admin.model.DbFile;
import org.millioncall.yueyoga.admin.model.Group;
import org.millioncall.yueyoga.admin.model.Hall;
import org.millioncall.yueyoga.admin.model.Role;
import org.millioncall.yueyoga.admin.model.User;
import org.millioncall.yueyoga.admin.model.UserDetail;
import org.millioncall.yueyoga.admin.service.DbFileService;
import org.millioncall.yueyoga.admin.service.GroupService;
import org.millioncall.yueyoga.admin.service.HallService;
import org.millioncall.yueyoga.admin.service.RoleService;
import org.millioncall.yueyoga.admin.service.UserDetailService;
import org.millioncall.yueyoga.admin.service.UserService;
import org.millioncall.yueyoga.common.GlobalConstants;
import org.millioncall.yueyoga.common.utils.FrontUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;

//--created by lisj on 2014.03.06
@Controller
public class UserAction extends BaseAction {
	private static Logger logger = LoggerFactory.getLogger(UserAction.class);
	private UserService userService;
	private DbFileService dbFileService;
	private GroupService groupService;
	private UserDetailService userDetailService;
	private RoleService roleService;
	private HallService hallService;

	public HallService getHallService() {
		return hallService;
	}

	public void setHallService(HallService hallService) {
		this.hallService = hallService;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public UserDetailService getUserDetailService() {
		return userDetailService;
	}

	public void setUserDetailService(UserDetailService userDetailService) {
		this.userDetailService = userDetailService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public DbFileService getDbFileService() {
		return dbFileService;
	}

	public void setDbFileService(DbFileService dbFileService) {
		this.dbFileService = dbFileService;
	}

	public GroupService getGroupService() {
		return groupService;
	}

	public void setGroupService(GroupService groupService) {
		this.groupService = groupService;
	}

	// 查询用户
	@RequestMapping(value = "/ajaxgetusersinpage.do")
	public void getUsersByPage(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = null;
		int start = 0;
		int limit = 20;

		String strStart = request.getParameter("start");
		if (strStart != null) {
			start = Integer.parseInt(strStart);
		}
		String pageSize = request.getParameter("limit");
		if (pageSize != null) {
			limit = Integer.parseInt(pageSize);
		}

		String[] paramNames = request.getParameterValues("paramNames");
		String[] paramValues = request.getParameterValues("paramValues");
		Map<String, Object> map = new HashMap<String, Object>();
		if (paramValues.length > 0) {
			for (int i = 0; i < paramValues.length; i++) {
				map.put(paramNames[i], paramValues[i]);
			}
		}
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<User> pl = userService.getUsersInPage(start, limit, map);
		if (pl.isEmpty()) {
			msg = "{'success':true,'total':0,'items':[]}";
		} else {
			StringBuilder sb = new StringBuilder("[");
			int totalUsers = 20;
			User loginUser = (User) request.getSession().getAttribute(
					GlobalConstants.LOGIN_USER_KEY);
			for (User user : pl) {
				if (user.getUsername().equals("admin")
						|| user.getUsername().equals("system")
						|| user.getUsername().equals(loginUser.getUsername())) {
					totalUsers--;
					continue;
				}
				sb.append("{");
				sb.append("'id':'" + user.getId() + "',");
				sb.append("'username':'" + user.getUsername() + "',");
				sb.append("'password':'" + user.getPassword() + "',");
				sb.append("'email':'" + user.getEmail() + "',");
				sb.append("'groups':'"
						+ userService.getCnStrGroups(user.getGroups()) + "',");
				sb.append("'status':" + user.getStatus() + ",");
				sb.append("'userenabled':'" + user.isEnabled() + "',");
				sb.append("'expired':" + user.isUsernameExpired() + ",");
				sb.append("'authoryexpired':" + user.isAuthorityExpired() + ",");
				sb.append("'locked':" + user.isLocked() + ",");
				sb.append("'expiretime':'" + user.getExpireTime() + "',");
				sb.append("'authorityexpiretime':'"
						+ user.getAuthorityExpireTime() + "',");
				sb.append("'createtime':'" + user.getCreateTime() + "',");
				sb.append("'lastlogintime':'" + user.getLastLoginTime() + "',");
				sb.append("'lastloginip':'" + user.getLastLoginIp() + "',");
				sb.append("'logintimes':" + user.getLoginTimes() + ",");
				sb.append("'groupsen':'" + user.getStrGroups() + "',");
				if (user.getHeadImgFileName() != null) {
					String imgPath = FrontUtil.createDbImageUrl(request,
							user.getHeadImgFileName());
					sb.append("'headimgfilepath':'" + imgPath + "',");
				} else {
					sb.append("'headimgfilepath':'',");
				}

				UserDetail ud = user.getUserDetail();
				sb.append("'name':'" + ud.getName() + "',");
				sb.append("'sex':'" + ud.getSex() + "',");
				sb.append("'birthday':'" + ud.getBirthday() + "',");
				sb.append("'homeaddress':'" + ud.getHomeAddress() + "',");
				sb.append("'workaddress':'" + ud.getWorkAddress() + "',");
				sb.append("'cardid':'" + ud.getCardId() + "',");
				sb.append("'phone':'" + ud.getPhone() + "',");
				sb.append("'mobile':'" + ud.getMobile() + "',");
				sb.append("'messagemail':'" + ud.getMessageMail() + "',");
				sb.append("'msn':'" + ud.getMsn() + "',");
				sb.append("'qq':'" + ud.getQq() + "',");
				sb.append("'job':'" + ud.getJob() + "',");
				sb.append("'trade':'" + ud.getTrade() + "',");

				String[] interest = request.getParameterValues("interest");
				String strins = null;
				if (interest != null && interest.length > 0) {
					List<String> interestlist = Arrays.asList(interest);
					for (String str : interestlist) {
						strins += str + ",";
					}
					if (strins != null) {
						strins = strins.substring(0, strins.length() - 1);
					}
				}
				sb.append("'interest':'" + strins + "',");

				sb.append("'contact':'" + ud.getContact() + "',");
				sb.append("'prestige':" + ud.getPrestige() + ",");
				sb.append("'credit':" + ud.getCredit() + ",");
				sb.append("'description':'" + ud.getDescription() + "',");

				Account account = user.getAccount();
				sb.append("'alipayaccount':'" + account.getAlipayAccount()
						+ "',");
				sb.append("'golds':" + account.getGolds() + ",");
				sb.append("'validgolds':" + account.getValidGolds() + ",");
				sb.append("'accountenabled':'" + account.isEnabled() + "'");
				sb.append("},");
			}
			String tmpusers = sb.toString();
			if (tmpusers.length() > 1) {
				tmpusers = tmpusers.substring(0, tmpusers.length() - 1);
			}
			tmpusers += "]";
			msg = "{'success':true,'total':" + totalUsers + ",'items':"
					+ tmpusers + "}";
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	// 取得所有用户组
	@RequestMapping(value = "/ajaxgetgroups.do")
	public void getGroups(HttpServletRequest request,
			HttpServletResponse response) {
		List<Group> groups = groupService.findAllGroups();
		String msg = "{'total':" + groups.size() + ",'items':";
		String tmpgroups = "[";
		for (Group group : groups) {
			tmpgroups += "{'groupid':'" + group.getId() + "',";
			tmpgroups += "'groupname':'" + group.getName() + "',";
			tmpgroups += "'namecn':'" + group.getNamecn() + "'},";
		}
		if (tmpgroups.length() > 1) {
			tmpgroups = tmpgroups.substring(0, tmpgroups.length() - 1);
		}
		tmpgroups += "]";
		msg += tmpgroups + "}";
		WebAppUtils.ajaxResponse(response, msg);
	}

	// 添加用户
	@RequestMapping(value = "/ajaxadduser.do")
	public void addUser(HttpServletRequest request, HttpServletResponse response) {
		String msg = null;
		String username = request.getParameter("user.username");
		String password = request.getParameter("user.password");

		if (StringUtils.isBlank(username)) {
			msg = "{'success':false,'msg':'用户名不可为空'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		if (username.length() < 3 || username.length() > 15) {
			msg = "{'success':false,'msg':'用户名长度应介于3-15之间'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		if (StringUtils.isBlank(password)) {
			msg = "{'success':false,'msg':'密码不可为空'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		if (password.length() < 6 || password.length() > 15) {
			msg = "{'success':false,'msg':'密码长度应介于6-15之间'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		if (!request.getParameter("confirmPwd").equals(password)) {
			msg = "{'success':false,'msg':'两次输入密码不一致'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		String email = request.getParameter("user.email");
		if (StringUtils.isBlank(email)) {
			msg = "{'success':false,'msg':'邮箱不可为空'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		User user = new User();
		user.setUsername(username);
		user.setPassword(EncryptUtils.encryptTextInMD5(password + "{"
				+ username + "}"));
		user.setEmail(email);

		String[] groupNames = request.getParameterValues("groups");
		List<Group> groups = groupService.findGroupsByGroupName(groupNames);
		user.setGroups(groups);
		user.setEnabled(request.getParameter("user.enabled").equals("true"));
		user.setLocked(request.getParameter("user.locked").equals("true"));

		// user.setStatus(Integer.parseInt(request.getParameter("user.status")));

		String expireTime = request.getParameter("user.expireTime");
		if (!StringUtils.isBlank(expireTime)) {
			user.setExpireTime(DateTimeUtils.getInstance().toDate(expireTime));
		} else {
			user.setExpireTime(null);
		}
		String authorityExpireTime = request
				.getParameter("user.authorityExpireTime");
		if (!StringUtils.isBlank(authorityExpireTime)) {
			user.setAuthorityExpireTime(DateTimeUtils.getInstance().toDate(
					authorityExpireTime));
		} else {
			user.setAuthorityExpireTime(null);
		}

		User u1 = userService.getUserByUsername(user.getUsername());
		if (u1 != null) {// 表示已存在此用户名
			msg = "{'success':false,'msg':'添加用户失败，此用户名已被注册'}";
		} else {
			User u2 = userService.getUserByEmail(user.getEmail());
			if (u2 != null) {// 表示已存在此邮件地址
				msg = "{'success':false,'msg':'添加用户失败，此电子邮箱已被注册'}";
			} else {
				UserDetail ud = new UserDetail();
				ud.setId(user.getId());// 必须有此句
				ud.setMessageMail(user.getEmail());

				Account account = new Account();
				account.setId(user.getId());// 必须有此句

				user.setUserDetail(ud);
				user.setAccount(account);
				if (userService.saveUser(user)) {
					msg = "{'success':true,'msg':'添加用户成功'}";
				} else {
					msg = "{'success':false,'msg':'添加用户失败，请稍候重试或联系管理员'}";
				}
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	// 批量删除用户
	@RequestMapping(value = "/ajaxdeleteuser.do")
	public void deleteUser(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = null;
		String ids = request.getParameter("ids");
		if (StringUtils.isBlank(ids)) {
			msg = "{'success':false,'msg':'未提交待删除用户的编号'}";
		} else {
			String[] arrids = ids.split(",");
			try {
				userService.deleteUsersByIds(arrids);
				msg = "{'success':true,'msg':'删除用户成功'}";
			} catch (RuntimeException re) {
				msg = "{'success':false,'msg':'删除用户失败，请稍候重试或联系管理员'}";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	// 编辑用户
	@SuppressWarnings("hiding")
	@RequestMapping(value = "/ajaxedituser.do")
	public void editUser(HttpServletRequest request,
			HttpServletResponse response) {
		String username = request.getParameter("user.username");
		String password = request.getParameter("user.password");

		String msg = null;
		User dbuser = userService.getUserByUsername(username);
		if (!StringUtils.isBlank(password)) {// 若输入了新密码
			String confirmPwd = request.getParameter("confirmPwd");
			if (!confirmPwd.equals(password)) {
				msg = "{'success':false,'msg':'两次输入的密码不一致'}";
				WebAppUtils.ajaxResponse(response, msg);
				return;
			} else {
				dbuser.setPassword(EncryptUtils.encryptTextInMD5(password + "{"
						+ username + "}"));
			}
		}

		// dbuser.setEmail(request.getParameter("user.email"));//修改基本信息时，用户邮箱不可更改
		String[] groupNames = request.getParameterValues("groups");
		List<Group> groups = groupService.findGroupsByGroupName(groupNames);
		dbuser.setGroups(groups);
		dbuser.setEnabled(request.getParameter("user.enabled").equals("true"));

		String expireTime = request.getParameter("user.expireTime");
		if (!StringUtils.isBlank(expireTime)) {
			dbuser.setExpireTime(DateTimeUtils.getInstance().toDate(expireTime));
		} else {
			dbuser.setExpireTime(null);
		}

		String authorityExpireTime = request
				.getParameter("user.authorityExpireTime");
		if (!StringUtils.isBlank(authorityExpireTime)) {
			dbuser.setAuthorityExpireTime(DateTimeUtils.getInstance().toDate(
					authorityExpireTime));
		} else {
			dbuser.setAuthorityExpireTime(null);
		}

		dbuser.setLocked(request.getParameter("user.locked").equals("true"));

		String imgsrc = request.getParameter("user.headimgsrc");
		if (!StringUtils.isBlank(imgsrc)) {
			String realPath = request.getServletContext().getRealPath(
					imgsrc.substring(request.getContextPath().length()));
			File file = new File(realPath);
			String ext = FilenameUtils.getExtension(file.getName())
					.toLowerCase();
			// 保存到数据库
			DbFile dbfile = null;
			try {
				dbfile = dbFileService.saveByExt(1, ext, new FileInputStream(
						file));
			} catch (FileNotFoundException e) {
				logger.error("文件未找到");
				WebAppUtils.ajaxResponse(response,
						"{'success':false,'msg':'文件未找到'}");
				return;
			} catch (IOException e) {
				logger.error("IO异常");
				WebAppUtils.ajaxResponse(response,
						"{'success':false,'msg':'IO异常'}");
				return;
			}
			dbuser.setHeadImgFile(dbfile);
		}

		if (userService.updateUser(dbuser)) {
			msg = "{'success':true,'msg':'更新用户成功'}";
		} else {
			msg = "{'success':false,'msg':'更新用户失败，请稍候重试或联系管理员'}";
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	// 仅修改密码
	@RequestMapping(value = "/ajaxmodifypwd.do")
	public void modifyPassword(HttpServletRequest request,
			HttpServletResponse response) {
		String originalPwd = request.getParameter("originalpwd");
		String newPwd = request.getParameter("newpassword");
		String confirmPwd = request.getParameter("confirmpwd");

		String msg = null;

		if (StringUtils.isBlank(originalPwd)) {
			msg = "{'success':false,'msg':'原始密码不可为空'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		if (StringUtils.isBlank(newPwd)) {
			msg = "{'success':false,'msg':'新密码不可为空'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		if (StringUtils.isBlank(confirmPwd)) {
			msg = "{'success':false,'msg':'确认密码不可为空'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		if (!confirmPwd.equals(newPwd)) {
			msg = "{'success':false,'msg':'两次输入的密码不一致'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		User currentUser = (User) request.getSession().getAttribute(
				GlobalConstants.LOGIN_USER_KEY);
		if (!currentUser.getPassword().equals(
				EncryptUtils.encryptTextInMD5(originalPwd + "{"
						+ currentUser.getUsername() + "}"))) {
			msg = "{'success':false,'msg':'原密码错误'}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}

		currentUser.setPassword(EncryptUtils.encryptTextInMD5(newPwd + "{"
				+ currentUser.getUsername() + "}"));

		if (userService.updateUser(currentUser)) {
			msg = "{'success':true,'msg':'密码修改成功'}";
		} else {
			msg = "{'success':false,'msg':'密码修改失败，请稍候重试或联系管理员'}";
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	// 编辑用户详细信息
	@RequestMapping(value = "/ajaxedituserdetail.do")
	public void editUserDetail(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = null;
		String username = request.getParameter("username");
		User dbuser = userService.getUserByUsername(username);
		if (dbuser == null) {
			WebAppUtils.ajaxResponse(response,
					"{'success':false,'msg':'找不到要修改的用户'}");
			return;
		}

		UserDetail ud = dbuser.getUserDetail();

		String name = request.getParameter("name");
		if (!StringUtils.isBlank(name)) {
			ud.setName(name);
		} else {
			ud.setName(null);
		}
		String sex = request.getParameter("sex");
		if (!StringUtils.isBlank(sex)) {
			ud.setSex(sex);
		}

		String birthday = request.getParameter("birthday");
		if (!StringUtils.isBlank(birthday)) {
			ud.setBirthday(DateTimeUtils.getInstance().toDate(birthday));
		} else {
			ud.setBirthday(null);
		}

		String homeaddr = request.getParameter("homeaddress");
		if (!StringUtils.isBlank(homeaddr)) {
			ud.setHomeAddress(homeaddr);
		} else {
			ud.setHomeAddress(null);
		}

		String workaddr = request.getParameter("workaddress");
		if (!StringUtils.isBlank(workaddr)) {
			ud.setWorkAddress(workaddr);
		} else {
			ud.setWorkAddress(workaddr);
		}

		String cardid = request.getParameter("cardid");
		if (!StringUtils.isBlank(cardid)) {
			ud.setCardId(cardid);
		} else {
			ud.setCardId(null);
		}

		String phone = request.getParameter("phone");
		if (!StringUtils.isBlank(phone)) {
			ud.setPhone(phone);
		} else {
			ud.setPhone(null);
		}

		String mobile = request.getParameter("mobile");
		if (!StringUtils.isBlank(mobile)) {
			ud.setMobile(mobile);
		} else {
			ud.setMobile(null);
		}

		String mail = request.getParameter("messagemail");
		if (!StringUtils.isBlank(mail)) {
			ud.setMessageMail(mail);
		} else {
			ud.setMessageMail(null);
		}

		String msn = request.getParameter("msn");
		if (!StringUtils.isBlank(msn)) {
			ud.setMsn(msn);
		} else {
			ud.setMsn(null);
		}

		String qq = request.getParameter("qq");
		if (!StringUtils.isBlank(qq)) {
			ud.setQq(qq);
		} else {
			ud.setQq(null);
		}

		String job = request.getParameter("job");
		if (!StringUtils.isBlank(job)) {
			ud.setJob(job);
		} else {
			ud.setJob(null);
		}

		String trade = request.getParameter("trade");
		if (!StringUtils.isBlank(trade)) {
			ud.setTrade(trade);
		} else {
			ud.setTrade(null);
		}

		String interest = request.getParameter("interest");
		if (!StringUtils.isBlank(interest)) {
			ud.setInterest(Arrays.asList(interest.split(",")));
		} else {
			ud.setInterest(null);
		}

		String contact = request.getParameter("contact");
		if (!StringUtils.isBlank(contact)) {
			ud.setContact(contact);
		} else {
			ud.setContact(null);
		}

		String prestige = request.getParameter("prestige");
		if (!StringUtils.isBlank(prestige)) {
			ud.setPrestige(Integer.parseInt(prestige));
		}

		String credit = request.getParameter("credit");
		if (!StringUtils.isBlank(credit)) {
			ud.setCredit(Integer.parseInt(credit));
		}

		String description = request.getParameter("description");
		if (!StringUtils.isBlank(description)) {
			ud.setDescription(description);
		} else {
			ud.setDescription(null);
		}

		Account account = dbuser.getAccount();
		String alipay = request.getParameter("alipayaccount");
		if (!StringUtils.isBlank(alipay)) {
			account.setAlipayAccount(alipay);
		} else {
			account.setAlipayAccount(null);
		}

		String golds = request.getParameter("golds");
		if (!StringUtils.isBlank(golds)) {
			account.setGolds(Float.parseFloat(golds));
		}

		String validgolds = request.getParameter("validgolds");
		if (!StringUtils.isBlank(validgolds)) {
			account.setValidGolds(Float.parseFloat(validgolds));
		}

		account.setEnabled(request.getParameter("accountenabled")
				.equals("true"));

		if (userService.updateUser(dbuser)) {
			msg = "{'success':true,'msg':'更新用户详细信息成功'}";
		} else {
			msg = "{'success':false,'msg':'更新用户详细信息失败，请稍候重试或联系管理员'}";
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	@RequestMapping(value = "/ajaxfindall.do")
	public void findAllUsers(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = "";
		Map<String, Object> map = new HashMap<String, Object>();
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group group : this.getUser(request).getGroups()) {
			groupIds.add(group.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		List<User> list = this.userService.findAllUsers(map);
		if (list.size() <= 0) {
			msg = "{'success':true,'total':0,'items':[]}";
			WebAppUtils.ajaxResponse(response, msg);
			return;
		}
		StringBuilder sb = new StringBuilder("[");
		for (User user : list) {
			sb.append("{");
			sb.append("'id':'" + user.getId() + "',");
			sb.append("'username':'" + user.getUsername() + "'");
			sb.append("},");
		}
		String str = sb.toString();
		str = str.substring(0, str.length() - 1);
		str += "]";
		msg = "{'success':true, 'total':" + list.size() + ", 'items':" + str
				+ "}";
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 跳到修改用户页面 **/
	@RequestMapping(value = "/toUpdateUser.jhtml")
	public String toUpdateUser(ModelMap context, HttpServletRequest request) {
		super.initFrontHeader(request, context);
		// 查询用户个人信息,显示到修改的页面
		User user = this.getUser(request);
		UserDetail userDetail = user.getUserDetail();
		context.put("id", userDetail.getId());
		context.put("name", userDetail.getName());
		context.put("job", userDetail.getJob());
		context.put("homeAddress", userDetail.getHomeAddress());
		context.put("workAddress", userDetail.getWorkAddress());
		context.put("phone", userDetail.getPhone());
		context.put("mobile", userDetail.getMobile());
		context.put("messageMail", userDetail.getMessageMail());
		context.put("msn", userDetail.getMsn());
		context.put("qq", userDetail.getQq());
		context.put("contact", userDetail.getContact());
		return "updateUser";
	}

	/** 修改用户页面 **/
	@RequestMapping(value = "/updateUser.jhtml")
	public String updateLiftClub(ModelMap map, HttpServletRequest request,
			HttpServletResponse response) {
		super.initFrontHeader(request, map);

		String id = request.getParameter("id");
		String username = request.getParameter("username");
		String job = request.getParameter("job");
		String homeAddress = request.getParameter("homeAddress");
		String workAddress = request.getParameter("workAddress");
		String userPhone = request.getParameter("userPhone");
		String userMobile = request.getParameter("userMobile");
		String userEmail = request.getParameter("userEmail");
		String userMsn = request.getParameter("userMsn");
		String userqq = request.getParameter("userqq");
		String userContact = request.getParameter("userContact");

		map.put("id", id);
		map.put("username", username);
		map.put("userEmail", job);
		map.put("homeAddress", homeAddress);
		map.put("workAddress", workAddress);
		map.put("userPhone", userPhone);
		map.put("userMobile", userMobile);
		map.put("userEmail", userEmail);
		map.put("userMsn", userMsn);
		map.put("userqq", userqq);
		map.put("userContact", userContact);

		if (userDetailService.updateUserDetail(map)) {
			map.put("msg", "success");
		} else {
			map.put("msg", "failure");
		}
		return "updateUser";
	}

	/** 跳到修改用户密码页面 **/
	@RequestMapping(value = "/toUpdatePassword.jhtml")
	public String toUpdatePassword(ModelMap context, HttpServletRequest request) {
		super.initFrontHeader(request, context);
		return "password_update";
	}

	/*
	 * 修改密码
	 */
	@RequestMapping(value = "/updatePassword.jhtml")
	public void updatePassword(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		super.initFrontHeader(request, model);
		String msg;
		User user = new User();
		user = (User) request.getSession().getAttribute(
				GlobalConstants.LOGIN_USER_KEY);
		String id = user.getId();
		String oldPwd = user.getPassword();
		String name = user.getUsername();
		String oldPassword = request.getParameter("oldPwd");// 旧密码
		String originalpwd = EncryptUtils.encryptTextInMD5(oldPassword + "{"
				+ name + "}");
		String newpassword = request.getParameter("pwd");// 新密码
		String newPwd = EncryptUtils.encryptTextInMD5(newpassword + "{" + name
				+ "}");
		if (oldPwd.equals(originalpwd)) {
			msg = "success";
			model.put("id", id);
			model.put("password", newPwd);
			if (userService.updatePassword(model)) {
				user.setPassword(originalpwd);
				request.getSession().setAttribute(
						GlobalConstants.LOGIN_USER_KEY, user);
			} else {
				msg = "error2";
			}
		} else {
			msg = "error";
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 进入用户管理 **/
	@RequestMapping(value = "/toBasicUsers.jhtml")
	public String toBasicUser(ModelMap map, HttpServletRequest request) {
		super.initFrontHeader(request, map);
		map.put("userGroups", groupService.findAllGroups());
		return "user_basic_search";
	}

	/** 进入组管理 **/
	@RequestMapping(value = "/toGroupUsers.jhtml")
	public String toGroupUser(ModelMap map, HttpServletRequest request) {
		super.initFrontHeader(request, map);
		// 查询所有角色,供选择
		List<Role> role = roleService.findRoleAll();
		map.put("listRole", role);
		return "user_group_search";
	}

	/** 查询所有的角色,供用户选择为某一个组指定角色 **/
	@RequestMapping(value = "/findRoles.jhtml")
	public void findRoles(HttpServletResponse response) {
		List<Role> roles = roleService.findRoleAll();
		WebAppUtils.ajaxResponse(response, JSON.toJSONString(roles));
	}

	/**
	 * 查询所有的用户组,供用户选择为某一个用户指定用户组
	 */
	@RequestMapping(value = "/findGroups.jhtml")
	public void fingGroups(HttpServletResponse response) {
		List<Group> groups = groupService.findAllGroups();
		WebAppUtils.ajaxResponse(response, JSON.toJSONString(groups));
	}

	/**
	 * 删除用户
	 */
	@RequestMapping(value = "/deleteUser.jhtml")
	public void deleteLiftClub(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		String msg;
		String[] arrIds = request.getParameterValues("ids[]");
		List<String> strIds = Arrays.asList(arrIds);
		List<String> intIds = new ArrayList<String>();
		for (String strId : strIds) {
			intIds.add(strId);
		}

		int i = this.userService.deleteUserById(intIds);
		msg = i > 0 ? "success" : "failure";
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 进入添加用户 **/
	@RequestMapping(value = "/toAddBasicUser.jhtml")
	public String toAddBasicUser(ModelMap model, HttpServletRequest request) {
		super.initFrontHeader(request, model);
		model.put("userGroups", groupService.findAllGroups());
		List<Hall> halls = hallService.findHalls();
		model.put("halls", halls);
		return "user_basic_add";
	}

	/** 进入添加组 **/
	@RequestMapping(value = "/toAddGroupUser.jhtml")
	public String toAddGroupUser(ModelMap model, HttpServletRequest request) {
		super.initFrontHeader(request, model);
		List<Role> role = roleService.findRoleAll();
		model.put("listRole", role);
		return "user_group_add";
	}

	/** 进入修改组 **/
	@RequestMapping(value = "/toUpdateGroupUser.jhtml")
	public String toUpdateGroupUser(Integer userId, ModelMap map,
			HttpServletRequest request) {
		super.initFrontHeader(request, map);

		List<Role> role = roleService.findRoleAll();
		map.put("listRole", role);
		if (userId != null) {
			Group group = groupService.findGroupById(userId);
			map.put("group", group);
		}
		return "user_group_edit";
	}

	/** 进入修改用户 **/
	@RequestMapping(value = "/toUpdateBasicUser.jhtml")
	public String toUpdateBasicUser(String userId, ModelMap map,
			HttpServletRequest request, HttpServletResponse response) {
		super.initFrontHeader(request, map);
		map.put("userGroups", groupService.findAllGroups());
		if (StringUtils.isNotBlank(userId)) {
			map.put("user", userService.findById(userId));
		} else {
			map.put("user", null);
		}
		
		List<Hall> halls = hallService.findHalls();
		map.put("halls", halls);
		
		return "user_basic_edit";
	}

	/** 修改组 **/
	@RequestMapping(value = "/updateGroupUser.jhtml")
	public String updateGroupUser(String userEnName, String userChName,
			String groupId, String description, String enabled, ModelMap map,
			HttpServletRequest request) {

		super.initFrontHeader(request, map);

		if (StringUtils.isNotBlank(userEnName)) {
			map.put("userEnName", userEnName);
		}
		if (StringUtils.isNotBlank(userChName)) {
			map.put("userChName", userChName);
		}
		if (StringUtils.isNotBlank(description)) {
			map.put("description", description);
		}
		if (StringUtils.isNotBlank(enabled)) {
			map.put("enabled", enabled);
		}
		if (groupId != null) {
			map.put("groupId", groupId);
		}
		if (groupService.updateGroup(map)) {
			map.put("msg", "success");
		} else {
			map.put("msg", "failure");
		}
		return "user_group_edit";
	}

	/** 添加组 **/
	@RequestMapping(value = "/addGroupUser.jhtml")
	public String addGroupUser(String userEnName, String userChName,
			String description, Integer enabled, ModelMap map,
			HttpServletRequest request) {
		super.initFrontHeader(request, map);
		Group enGroup = groupService.findGroupIdByName(userEnName);
		Group chGroup = groupService.findGroupByChName(userChName);
		if (enGroup!=null) {
			map.put("msg", "yicunzai");
			return "redirect:toAddGroupUser.jhtml";
		}
		if (chGroup!=null) {
			map.put("msg", "chyicunzai");
			return "redirect:toAddGroupUser.jhtml";
		}
		if (StringUtils.isNotBlank(userEnName)) {
			map.put("userEnName", userEnName);
		}
		if (StringUtils.isNotBlank(userChName)) {
			map.put("userChName", userChName);
		}
		if (StringUtils.isNotBlank(description)) {
			map.put("description", description);
		}
		if (enabled != null) {
			map.put("enabled", enabled);
		}
		// 添加进组
		if (groupService.saveGroup(map)) {
			// 根据name查询新插入组的ID,用来关联role
			/*Group gId = groupService.findGroupIdByName(userEnName);
			int groId = gId.getId();
			map.put("groId", groId);
			// group关联role
			if (groupService.saveGroupRole(map)) {
				map.put("msg", "success");
			} else {
				map.put("msg", "failure");
			}*/
			map.put("msg", "success");
		} else {
			map.put("msg", "failure");
		}
		return "user_group_add";
	}

	/** 添加,修改用户 **/
	@RequestMapping(value = "/addBasicUser.jhtml")
	public String updateBasicUser(String userId, String username,
			String groupId, String password, String apassword, String email,
			String expireTime, String name,String organization, String sex, String birthday,
			String phone, String address, ModelMap model,
			HttpServletRequest request) {
		super.initFrontHeader(request, model);
		Map<String, Object> map = new HashMap<String, Object>();
		User user = new User();
		model.put("userGroups", groupService.findAllGroups());
		// 判断是否为修改
		if (StringUtils.isBlank(userId)) {
			if (StringUtils.isNotBlank(username)) {
				user.setUsername(username);
				List<User> list = userService.findByProperty("username",
						username);
				if (!list.isEmpty()) {
					model.put("msg", "yizhuce");
					return "redirect:toAddBasicUser.jhtml";
				}
			} else {
				model.put("msg", "notnull");
				return "user_basic_add";
			}
			if (StringUtils.isNotBlank(password)) {
				if (!password.equals(apassword)) {
					model.put("msg", "mimabuyizhi");
					return "redirect:toAddBasicUser.jhtml";
				}
				user.setPassword(EncryptUtils.encryptTextInMD5(password + "{"
						+ username + "}"));
			} else {
				model.put("msg", "mimanotnull");
				return "user_basic_add";
			}
			if (StringUtils.isNotBlank(email)) {
				user.setEmail(email);
				List<User> list = userService.findByProperty("email", email);
				if (!list.isEmpty()) {
					model.put("msg", "email");
					return "redirect:toAddBasicUser.jhtml";
				}
			}
			// else {
			// map.put("msg", "邮箱不为空!");
			// return "user_basic_add";
			// }
		} else {
			user = this.userService.findById(userId);
		}

		if (StringUtils.isNotBlank(groupId)) {
			user.setGroupId(groupId);
		}

		if (StringUtils.isNotBlank(expireTime)) {
			user.setExpireTime(DateTimeUtils.getInstance().parse(expireTime,
					"yyyy-MM-dd"));
		}
		if (StringUtils.isNotBlank(organization)) {
			user.setOrganizationId(organization);
		}
		UserDetail userDetail = new UserDetail();
		if (!StringUtils.isBlank(userId)) {
			userDetail = this.userDetailService.findUserDetailById(userId);
		}
		if (StringUtils.isNotBlank(name)) {
			userDetail.setName(name);
		}
		if (StringUtils.isNotBlank(sex)) {
			userDetail.setSex(sex);
		}
		if (StringUtils.isNotBlank(birthday)) {
			userDetail.setBirthday(DateTimeUtils.getInstance().parse(birthday,
					"yyyy-MM-dd"));
		}
		if (StringUtils.isNotBlank(phone)) {
			userDetail.setPhone(phone);
		}
		if (StringUtils.isNotBlank(address)) {
			userDetail.setHomeAddress(address);
		}
		user.setUserDetail(userDetail);
		user.setGroupId("users");
		map.put("userGroups", groupService.findAllGroups());
		List<Hall> halls = hallService.findHalls();
		model.put("halls", halls);
		if (StringUtils.isBlank(userId)) {
			if (userService.saveUser(user)) {
				model.put("msg", "success");
			} else {
				model.put("msg", "failure");
			}
			return "user_basic_add";
		} else {
			if (userService.updateUser(user)) {
				model.put("msg", "success");
			} else {
				model.put("msg", "failure");
			}
			return "user_basic_edit";
		}
	}

	/** 查询组 **/
	@RequestMapping(value = "/searchGroupUsers.jhtml")
	public String searchGroupUsers(String userEnName, String userChName,
			Integer role, String description, Integer Enabled, ModelMap map,
			HttpServletRequest request) {

		List<Hall> halls = hallService.findHalls();
		map.put("halls", halls);

		List<Role> roles = roleService.findRoleAll();
		map.put("groupRole", roles);
		super.initFrontHeader(request, map);

		int start = 0;
		int limit = 10;
		String pageNo = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");

		if (StringUtils.isNotBlank(pageSize)) {
			limit = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNotBlank(pageNo)) {
			start = (Integer.parseInt(pageNo) - 1) * limit;
		}
		
		if (StringUtils.isNotBlank(userEnName)) {
			map.put("userEnName", userEnName);
		}
		if (StringUtils.isNotBlank(userChName)) {
			map.put("userChName", userChName);
		}
		if (StringUtils.isNotBlank(description)) {
			map.put("description", description);
		}
		if (Enabled != null) {
			map.put("Enabled", Enabled);
		}
		if (role != null) {
			map.put("role", role);
		}
		PaginatedList<Group> pl = groupService.getGroupsInPage(start, limit,
				map);
		map.put("groups", pl);
		return "user_group_search";
	}

	/**
	 * 删除组
	 */
	@RequestMapping(value = "/deleteGroup.jhtml")
	public void deleteGroups(HttpServletRequest request,
			HttpServletResponse response) {
		String msg = null;
		String ids = request.getParameter("ids");
		if (StringUtils.isBlank(ids)) {
			msg = "{'success':false,'msg':'未提交删除组'}";
		} else {
			String[] arrids = ids.split(",");
			int[] id = new int[arrids.length];
			for (int i = 0; i < arrids.length; i++) {
				if (!StringUtils.isEmpty(arrids[i])) {
					id[i] = Integer.parseInt(arrids[i]);
				}
			}
			try {
				groupService.deleteGroupById(id);// 删除组
				groupService.deleteGroupRoleById(id);// 删除组跟角色的关系
				groupService.deleteGroupUserById(id);// 删除组跟用户的关系
				msg = "true";
			} catch (RuntimeException re) {
				msg = "false";
			}
		}
		WebAppUtils.ajaxResponse(response, msg);
	}

	/** 查询用户 **/
	@RequestMapping(value = "/searchBasicUsers.jhtml")
	public String searchBasicUsers(String name, String userName, String phone,
			String group, ModelMap map, HttpServletRequest request) {

		super.initFrontHeader(request, map);

		map.put("userGroups", groupService.findAllGroups());
		int start = 0;
		int limit = 10;
		String pageNo = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");

		if (StringUtils.isNotBlank(pageSize)) {
			limit = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNotBlank(pageNo)) {
			start = (Integer.parseInt(pageNo) - 1) * limit;
		}
		if (StringUtils.isNotBlank(userName)) {
			map.put("username", userName);
		}
		if (StringUtils.isNotBlank(name)) {
			map.put("name", name);
		}
		if (StringUtils.isNotBlank(phone)) {
			map.put("phone", phone);
		}
		if (StringUtils.isNotBlank(group)) {
			map.put("group", group);
		}
		List<Integer> groupIds = new ArrayList<Integer>();
		for (Group groupg : this.getUser(request).getGroups()) {
			groupIds.add(groupg.getId());
		}
		map.put("groups", groupIds);
		map.put("hallcode", this.getUser(request).getOrganizationId());
		PaginatedList<User> pl = userService.getUsersInPage(start, limit, map);
		map.put("pl", pl);
		return "user_basic_search";
	}

	/**
	 * 赋予用户所属组
	 */
	@RequestMapping(value = "/grantGroups.jhtml")
	public String grantUsertoGroup(String userId, String[] groupId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap map) {
		User user = new User();
		super.initFrontHeader(request, map);
		String msg = null;
		if (StringUtils.isBlank(userId) || groupId.length == 0
				&& groupId == null) {
			msg = "获取数据失败!";
		} else {
			String enName = groupService.findEnNameById(groupId);
			user.setGroupName(enName);
			user.setId(userId);
			if (groupService.saveGrantGroups(userId, groupId)) {
				if (userService.updateUserGroups(user)) {
					map.put("groupMsg", "success");
				}
			} else {
				map.put("groupMsg", "failure");
			}
		}
		return "redirect:searchBasicUsers.jhtml";
		// WebAppUtils.ajaxResponse(response, msg);
	}

	/**
	 * 赋予组角色
	 * 
	 * @param response
	 */
	@RequestMapping(value = "/grantRoles.jhtml")
	public String grantRolesToGroup(String groupId, String roleId,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap map) {
		super.initFrontHeader(request, map);
		String msg = null;
		
		if (StringUtils.isBlank(groupId) || StringUtils.isBlank(roleId)) {
			msg = "获取数据失败!";
		} else {
			String[] roles = roleId.split(",");
			roleId = "";
			for (String r : roles) {
				if (StringUtils.isNotBlank(r)) 
					roleId += r + ",";
			}
			roleId = roleId.substring(0, roleId.length() - 1);
			if (StringUtils.isBlank(roleId)) {
				map.put("groupMsg", "failure");
			} else {
				if (groupService.savegrantRoles(groupId, roleId)) {
					map.put("groupMsg", "success");
				} else {
					map.put("groupMsg", "failure");
				}
			}
		}
		return "redirect:searchGroupUsers.jhtml";
		// WebAppUtils.ajaxResponse(response, msg);

	}

	/**
	 * 赋予组会馆
	 */
	@RequestMapping(value = "/grantHall.jhtml")
	public String grantHall(String groupId, String hallId,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap map) {
		super.initFrontHeader(request, map);
		String msg = null;
		if (StringUtils.isBlank(groupId) || StringUtils.isBlank(hallId)) {
			msg = "获取数据失败!";
		} else {
			if (groupService.saveGrantHall(groupId, hallId)) {
				map.put("groupMsg", "success");
			} else {
				map.put("groupMsg", "failure");
			}
		}
		return "redirect:searchGroupUsers.jhtml";
		// WebAppUtils.ajaxResponse(response, msg);
	}

	/**
	 * 查询所属角色
	 */
	@RequestMapping(value = "/findUserRoleById.jhtml")
	public void findUserRoleById(HttpServletResponse response, String gpId,
			Map<String, Object> map) {
		List<Role> findRolesByGroupId = roleService.findRolesByGroupId(gpId);
		String msg = "{'success':true, 'msg':'"
				+ JSON.toJSONString(findRolesByGroupId) + "'}";
		WebAppUtils.ajaxResponse(response, msg);
	}

	/**
	 * 查询所属会馆
	 */
	@RequestMapping(value = "/findUserHallById.jhtml")
	public void findUserHallById(HttpServletRequest request,
			HttpServletResponse response, String groupId,
			Map<String, Object> map) {
		List<Hall> findUserHallById = hallService.findHallsByGroupId(groupId);
		String msg = "{'success':true, 'msg':'"
				+ JSON.toJSONString(findUserHallById) + "'}";
		WebAppUtils.ajaxResponse(response, msg);
	}

	/**
	 * 查询用户所属组
	 */
	@RequestMapping(value = "/findUserGroupById.jhtml")
	public void findUserGroupById(HttpServletRequest request,
			HttpServletResponse response, String userId, Map<String, Object> map) {
		List<Group> findUserGroupById = groupService.findByUserId(userId);
		String msg = "{'success':true, 'msg':'"
				+ JSON.toJSONString(findUserGroupById) + "'}";
		WebAppUtils.ajaxResponse(response, msg);
	}

}
